﻿/**************************************************************
 *
 * 唯一标识：548b3d37-371e-4b0a-b726-20a58737ee3c
 * 命名空间：Sgr.UPMS.Application.Commands.Users
 * 创建时间：2023/8/27 11:46:15
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：更新用户命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.UPMS.Domain.Departments;
using Sgr.UPMS.Domain.Duties;
using Sgr.UPMS.Domain.Users;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Users
{
    /// <summary>
    /// 更新用户命令处理器
    /// </summary>
    public class UpdateUserCommandHandle : IRequestHandler<UpdateUserCommand, CommandResult<bool>>
    {
        private readonly IUserRepository _userRepository;
        private static readonly string[] UserIncludes = { "Duties", "Roles" };

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userRepository">用户仓储</param>
        public UpdateUserCommandHandle(
            IUserRepository userRepository)
        {
            _userRepository = userRepository;
        }

        /// <summary>
        /// 处理更新用户命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<CommandResult<bool>> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
        {
            // 查找用户实体
            var user = await _userRepository.GetAsync(request.UserId, UserIncludes, cancellationToken);

            // 如果找不到用户，返回NotFound结果
            if (user == null)
                return CommandResult.NotFound<bool>("未找到指定的用户");

            // 设置用户信息：名称、部门、岗位
            user.SetUserInfo(request.UserName, request.Gender, user.QQ, user.BirthDay);
            user.SetDepartment(request.DepartmentId, "");
            user.SetPrimaryDuty(request.PrimaryDutyId, "");

            // 绑定所属角色
            if (request.RoleIds != null)
                user.DifferenceUpdateRoles(request.RoleIds!);

            user.ChangeEntityStates(request.State);

            // 更新到仓储
            await _userRepository.UpdateAsync(user, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "用户信息更新成功");
        }
    }
}